﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Win32;
using SuperMicroWave.Common;
using SuperMicroWave.Models;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Collections.ObjectModel;

namespace SuperMicroWave.ViewModels
{
    public partial class MethodViewModel : ObservableRecipient
    {
        public MethodViewModel() 
        {
            LoadMethodData();
        }


        #region 全局变量

        #endregion


        #region 数据源
        [ObservableProperty]
        public ObservableCollection<HeatFlowModel> heatFlowItems;
        [ObservableProperty]
        public double prePressure;
        [ObservableProperty]
        public double endTemp;

        [ObservableProperty]
        public string methodName;

        [ObservableProperty]
        public string methodFilePath;

        [ObservableProperty]    
        private bool isEditEnable = true;
        private bool CanSaveEnable => !IsEditEnable;
        #endregion


        #region 命令函数
        [RelayCommand(CanExecute = nameof(IsEditEnable))]
        public void SwitchAutoClean()
        {
            if (GlobalValue.NowState.CurState != ConnectInfo.InsState.DEV_IDLE)
            {
                MessageBox.Show("请等待升温流程结束!", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            GlobalValue.sysParams.MethodFilePath = "./Xml/自动清洗.xml";
            GlobalValue.sysParams.MethodName = Path.GetFileNameWithoutExtension(GlobalValue.sysParams.MethodFilePath);

            MethodModel.ReadMethodXML(GlobalValue.sysParams.MethodFilePath, ref GlobalValue.methodData);
            LoadMethodData();

            INIFile.InifileWriteValue("SYSPARAMS", "MethodName", MethodName, INIFile.iniPath);
            INIFile.InifileWriteValue("SYSPARAMS", "MethodFilePath", MethodFilePath, INIFile.iniPath);

            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<bool>(true));  //通知绘图界面

            MessageBox.Show("打开成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        [RelayCommand(CanExecute = nameof(IsEditEnable))]
        public void OpenMethod()
        {
            if(GlobalValue.NowState.CurState != ConnectInfo.InsState.DEV_IDLE)
            {
                MessageBox.Show("请等待升温流程结束!", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            OpenFileDialog openFileDialog = new()
            {
                Filter = "Method Files (*.xml)|*.xml"
            };
            if (openFileDialog.ShowDialog() == true)
            {  
                GlobalValue.sysParams.MethodFilePath = openFileDialog.FileName;
                GlobalValue.sysParams.MethodName = Path.GetFileNameWithoutExtension(GlobalValue.sysParams.MethodFilePath);
               
                MethodModel.ReadMethodXML(GlobalValue.sysParams.MethodFilePath, ref GlobalValue.methodData);
                LoadMethodData();

                INIFile.InifileWriteValue("SYSPARAMS", "MethodName", MethodName, INIFile.iniPath);
                INIFile.InifileWriteValue("SYSPARAMS", "MethodFilePath", MethodFilePath, INIFile.iniPath);

                WeakReferenceMessenger.Default.Send(new ValueChangedMessage<bool>(true));  //通知绘图界面

                MessageBox.Show("打开成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        [RelayCommand(CanExecute = nameof(IsEditEnable))]
        public void EditMethod()
        {
            if (GlobalValue.NowState.CurState != ConnectInfo.InsState.DEV_IDLE)
            {
                MessageBox.Show("请等待升温流程结束!", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            IsEditEnable = false;
            NotifyButtonCanExecute();
        }

        [RelayCommand(CanExecute = nameof(CanSaveEnable))]
        public void SaveMethod()
        {
            if (!CheckHeatFlow())
            {
                MessageBox.Show("目标温度应低于850℃", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string name = Path.GetFileNameWithoutExtension(MethodFilePath);
            string path = Path.GetDirectoryName(MethodFilePath)!;
            if(MethodName != name)
            {
                string newPath = Path.Combine(path, MethodName) + ".xml";
                if(File.Exists(newPath))
                {
                    MessageBox.Show("文件名重复!", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
                File.Move(MethodFilePath, newPath);
                MethodFilePath = newPath;

                GlobalValue.NowState.IsAutoClean = MethodName == "自动清洗";
                INIFile.InifileWriteValue("SYSPARAMS", "MethodName", MethodName, INIFile.iniPath);
                INIFile.InifileWriteValue("SYSPARAMS", "MethodFilePath", MethodFilePath, INIFile.iniPath);
            }

            try
            {
                CopyMethodData();
                MethodModel.WriteMethodXML(MethodFilePath, GlobalValue.methodData);
                
                WeakReferenceMessenger.Default.Send(new ValueChangedMessage<bool>(true));  //通知绘图界面
            
                IsEditEnable = true;
                NotifyButtonCanExecute();

                MessageBox.Show("保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("方法保存失败：" + ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        [RelayCommand(CanExecute = nameof(CanSaveEnable))]
        public void SaveAsMethod()
        {
            if (!CheckHeatFlow())
            {
                MessageBox.Show("目标温度应低于850℃", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            SaveFileDialog sfd = new()
            {
                Filter = "Method Files (*.xml)|*.xml"
            };
            if (sfd.ShowDialog() == true)
            {
                string desFilePath = sfd.FileName;
                File.Copy(MethodFilePath, desFilePath);  //复制文件到目标路径

                MethodFilePath = desFilePath;        //显示另存为的路径
                MethodName = Path.GetFileNameWithoutExtension(desFilePath);   //显示另存为的文件名
                CopyMethodData();
                MethodModel.WriteMethodXML(MethodFilePath, GlobalValue.methodData);  //数据写入

                GlobalValue.NowState.IsAutoClean = MethodName == "自动清洗";
                INIFile.InifileWriteValue("SYSPARAMS", "MethodName", MethodName, INIFile.iniPath);
                INIFile.InifileWriteValue("SYSPARAMS", "MethodFilePath", MethodFilePath, INIFile.iniPath);

                WeakReferenceMessenger.Default.Send(new ValueChangedMessage<bool>(true));  //通知绘图界面

                IsEditEnable = true;
                NotifyButtonCanExecute();

                MessageBox.Show("保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        [RelayCommand]
        public void AddFlow(object o)
        {
            int index = (int)o;

            HeatFlowModel hfm = new HeatFlowModel();
            hfm.Index = index + 1;
            hfm.AddFont = "+";
            hfm.DelFont = "-";

            for(int i = index; i < HeatFlowItems.Count; i++)
            {
                HeatFlowItems[i].Index++;
            }
            HeatFlowItems.Insert(index, hfm); 
        }

        [RelayCommand]
        public void DelFlow(object o)
        {
            int index = (int)o;

            HeatFlowModel hfm = HeatFlowItems.First(s => s.Index == index);
            HeatFlowItems.Remove(hfm);

            for (int i = 0; i < HeatFlowItems.Count; i++)
            {
                HeatFlowItems[i].Index = i + 1;
            }
        }
        #endregion


        #region 功能函数
        public void LoadMethodData()
        {
            PrePressure = GlobalValue.methodData.PrePressure;
            EndTemp = GlobalValue.methodData.EndTemp;
            HeatFlowItems = new ObservableCollection<HeatFlowModel>(GlobalValue.methodData.HeatFlowItems);

            MethodName = GlobalValue.sysParams.MethodName;
            MethodFilePath = GlobalValue.sysParams.MethodFilePath;

            GlobalValue.NowState.IsAutoClean = MethodName == "自动清洗";

            IsEditEnable = true;
        }

        public void CopyMethodData()
        {
            GlobalValue.methodData.PrePressure = PrePressure;
            GlobalValue.methodData.EndTemp = EndTemp;
            GlobalValue.methodData.HeatFlowItems = new ObservableCollection<HeatFlowModel>(HeatFlowItems);  
            
            GlobalValue.sysParams.MethodFilePath = MethodFilePath;
            GlobalValue.sysParams.MethodName = MethodName;
        }

        /// <summary>
        /// 检查流程数据
        /// </summary>
        public bool CheckHeatFlow()
        {
            foreach (var item in HeatFlowItems)
            {
                if(item.TargetTemp >= 850)
                {
                    return false;
                }
            }
            return true;
        }

        public void NotifyButtonCanExecute()
        {
            EditMethodCommand.NotifyCanExecuteChanged();
            OpenMethodCommand.NotifyCanExecuteChanged();
            SaveAsMethodCommand.NotifyCanExecuteChanged();
            SaveMethodCommand.NotifyCanExecuteChanged();
            SwitchAutoCleanCommand.NotifyCanExecuteChanged();
        }
        #endregion
    }
}
